﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using fuzhu;
using LH.Model.PU;
using XXX.Common;
using SqlSugar;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Utilities.Collections;
using System.Numerics;
using Microsoft.EntityFrameworkCore.Metadata;
using SqlSuarEntity;
using XXX.Models;
using Microsoft.Extensions.Options;
using System.Reflection.Emit;
using System.ComponentModel;
using XXX.Models.XXXEntities;
using Yonyou.U8.BO;
using XXX.Models.WDFT;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using ZDEntity;
using static XXX.Models.MO.API_Morder;
using XXX.Models.MO;

namespace XXX.Bo.ViewModel
{
   public class BOMVM:API_BOM
    {

        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string cacc { get; set; }
        public string xmlConfig { get; set; }
        public BOMVM()
        {
            //conStr
            conStr = CanShu.conStr;
            cacc = CanShu.cZT;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }
        /// <summary>
        /// 插入BOM
        /// </summary>
        /// <param name="model"></param>
        /// <param name="cacc"></param>
        /// <param name="conStr"></param>
        /// <param name="isupdate"></param>
        /// <returns></returns>
        public string Insert( )
        {


            try
            {
                //构建插入表
                //取得账套号

                string cAcc = cacc;
                //id值减去获取条件，后续在新增
                int[] arrayBomid = DbHelper2.GetU8ID(cAcc, "bom_bom", 1, conStr);
                int iBomid = arrayBomid[1];

                InventoryVM invm = new InventoryVM();
                //bom表
                bom_bom bom = new bom_bom();
                bom.BomId = iBomid;
                bom.Version = cVersion;
                bom.VersionDesc = cVersionDesc;
                bom.VersionEffDate = dVersionEffDate;
                bom.VersionEndDate = DbHelper.GetDbDate("2099-12-31");
                bom.BomType = 1;
                bom.CreateUser =cCreateUser;
                bom.CreateDate = dCreateDate;
                bom.RelsUser = cRelsUser;
                bom.RelsDate = dRelsDate;
                bom.CreateTime = DateTime.Now;
                bom.RelsTime = DateTime.Now;
                bom.VTid = 30442;
                bom.Status = 3;
                bom.OrgStatus = 1;
                bom.iPrintCount = 0;
                bom.IsWFControlled = 0;
                bom.iVerifyState = 0;
                bom.iReturnCount = 0;
                bom.AuditStatus = 1;
                bom.bProcessMaterial = false;
                bom.bProcessProduct = false;
                bom.UpdCount = 0;

                //bomparent表
                bom_parent bomParent = new bom_parent();
                bomParent.AutoId = Guid.NewGuid();
                bomParent.BomId = iBomid;


                RetModel2 retparent = invm.GetPartidNoFree(cParentCode);
                if (retparent.code == 200)
                {
                    bomParent.ParentId = DbHelper.GetDbInt(retparent.data);
                }
                else
                {
                    throw new Exception(cParentCode + retparent.message);
                }

                bomParent.ParentScrap = DbHelper.GetDbdecimal("0.00");
                bomParent.SharingPartId = 0;
                //bom_opcomponent表
                List<bom_opcomponent> bomopcomponentList;
                List<bom_opcomponentopt> bomopcomponentoptList;
                List<bom_opcomponentsub> lstsub;
                BulidBOMChild(iBomid, out bomopcomponentList, out bomopcomponentoptList, out lstsub);
                SqlSugarClient Tardb = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = CanShu.conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                });
                try
                {
                    Tardb.BeginTran();
                    Tardb.Insertable(bom).ExecuteCommand();
                    Tardb.Insertable(bomParent).ExecuteCommand();
                    Tardb.Insertable(bomopcomponentoptList).ExecuteCommand();
                    Tardb.Insertable(bomopcomponentList).ExecuteCommand();
                    Tardb.Insertable(lstsub).ExecuteCommand();
                    Tardb.CommitTran();
                }
                catch (Exception ex)
                {
                    Tardb.RollbackTran();
                    throw ex;
                }

            }
            catch (Exception exception)
            {

                return "导入失败：" + exception.Message;
            }

            return "ok";
        }

        /// <summary>
        /// 构建BOM子表
        /// </summary> 
        /// <param name="iBomid"></param>
        /// <param name="bomopcomponentList"></param>
        /// <param name="bomopcomponentoptList"></param>
        /// <param name="lstsub"></param>
        /// <exception cref="Exception"></exception>
        private void BulidBOMChild(int iBomid,out List<bom_opcomponent> bomopcomponentList, out List<bom_opcomponentopt> bomopcomponentoptList, out List<bom_opcomponentsub> lstsub)
        {
            int icnt = ItemList.Count;
            bomopcomponentList = new List<bom_opcomponent>();
            bomopcomponentoptList = new List<bom_opcomponentopt>();
            lstsub = new List<bom_opcomponentsub>();
            int[] arrayBomChildid = DbHelper2.GetU8ID(cacc, "bom_opcomponent", icnt, conStr);
            int iopcomponentid = arrayBomChildid[1] - icnt;
            int[] arrayBomChildoptid = DbHelper2.GetU8ID(cacc, "bom_opcomponentopt", icnt, conStr);
            int iopcomponentoptid = arrayBomChildoptid[1] - icnt;
            InventoryVM invm = new InventoryVM();
            for (int i = 0; i < ItemList.Count; i++)
            {
            
                bom_opcomponent bomopcomponent = new bom_opcomponent();

                bomopcomponent.BomId = iBomid;
                bomopcomponent.OpComponentId = iopcomponentid + 1 + i;
                bomopcomponent.OptionsId = iopcomponentoptid + 1 + i;
                RetModel2 retchild = invm.GetPartidNoFree(ItemList[i].cChildCode);
                if (retchild.code == 200)
                {
                    bomopcomponent.ComponentId = DbHelper.GetDbInt(retchild.data);
                }
                else
                {
                    throw new Exception(ItemList[i].cChildCode + retchild.message);
                }
                bomopcomponent.OpSeq = "0000";
                bomopcomponent.SortSeq = ItemList[i].cSortSeq;
                bomopcomponent.EffBegDate = dVersionEffDate;
                bomopcomponent.EffEndDate = DbHelper.GetDbDate("2099-12-31");
                bomopcomponent.FVFlag = 1;
                bomopcomponent.BaseQtyN = DbHelper.GetDbdecimal(ItemList[i].dBaseQtyN);
                bomopcomponent.BaseQtyD = 1;
                bomopcomponent.ByproductFlag = false;
                bomopcomponent.CompScrap = 0;
                bomopcomponent.ProductType = 1;
                bomopcomponent.bProcessProduct = false;
                bomopcomponent.bProcessMaterial = false;
                bomopcomponent.RecursiveFlag = false;
                //工站名称
                //bomopcomponent.Define31 = ItemList[i].opName;
                //处理辅助计量单位
                InvAuxCom invAuxCom = invm.GetAuxEntity(ItemList[i].cChildCode);
                if (invAuxCom != null && !string.IsNullOrEmpty(bomopcomponent.AuxUnitCode))
                {
                    bomopcomponent.AuxUnitCode = invAuxCom.cSTComUnitCode;
                    bomopcomponent.ChangeRate = DbHelper.GetDbdecimal(invAuxCom.iChangRate);
                    bomopcomponent.AuxBaseQtyN = DbHelper.GetDbdecimal(ItemList[i].dBaseQtyN) / DbHelper.GetDbdecimal(invAuxCom.iChangRate);
                }

                bomopcomponentList.Add(bomopcomponent);
                //                    INSERT INTO bom_opcomponentopt(OptionsId, Offset, WIPType, AccuCostFlag, DrawDeptCode, Whcode, OptionalFlag, MutexRule, PlanFactor, CostWIPRel)
                //select U8_Optionsid,0,3,1,'',NULL,0,2,100,0 FROM ZDY_BOM_DAORU   WHERE bs = 0   and taskcode = @taskcode  and ParentCode = @u8parentcode

                bom_opcomponentopt bomopcomponentpot = new bom_opcomponentopt();
                bomopcomponentpot.OptionsId = iopcomponentoptid + 1 + i;
                bomopcomponentpot.Offset = 0;
                bomopcomponentpot.WIPType = 3;
                bomopcomponentpot.AccuCostFlag = true;
                bomopcomponentpot.OptionalFlag = false;
                bomopcomponentpot.MutexRule = 2;
                bomopcomponentpot.PlanFactor = 100;
                bomopcomponentpot.CostWIPRel = false;
                bomopcomponentpot.FeatureRel = false;
                bomopcomponentpot.DrawDeptCode = "";
                bomopcomponentoptList.Add(bomopcomponentpot);



                if (ItemList[i].subList!=null)
                {
                    //写替代料
                    List<string> lstsubinv = new List<string>();
                    for (int t = 0; t< ItemList[i].subList.Count; t++)
                    {
                        bom_opcomponentsub bomopcomponentsub = new bom_opcomponentsub();
                        int[] arraysubid = DbHelper2.GetU8ID(cacc, "bom_opcomponentsub", icnt,conStr);
                        bomopcomponentsub.ComponentSubId = arraysubid[1];
                        bomopcomponentsub.OpComponentId = bomopcomponent.OpComponentId;

                        bomopcomponentsub.Sequence = t + 1;
                        bomopcomponentsub.Factor = 1;
                        RetModel2 retchildsub1 = invm.GetPartidNoFree(ItemList[i].subList[t].cSubCode);
                        if (retchildsub1.code == 200)
                        {
                            bomopcomponentsub.PartId = DbHelper.GetDbInt(retchildsub1.data);
                        }
                        else
                        {
                            throw new Exception(lstsubinv[t] + retchildsub1.message);
                        }
                        bomopcomponentsub.EffBegDate = dVersionEffDate;
                        bomopcomponentsub.EffEndDate = DbHelper.GetDbDate("2099-12-31");
                        bomopcomponentsub.ReplaceFlag = false;
                        //arrayBomChildoptid[0]  ;
                        lstsub.Add(bomopcomponentsub);
                    }
                }
               
              


                 


            }
        }


        /// <summary>
        ///  根据HuaJinMorder更改生产订单
        /// </summary>
        /// <param name="dtMo">订单表头信息</param>
        /// <param name="dtOrderDetail">订单行</param>
        /// <param name="dtAllocate">订单子件</param>
        /// <returns></returns>
        public string UpdateBOM()
        {

            try
            {
                //构建插入表
                //取得账套号 
           
                //先删除子表，
                SqlsugarHelper.Instance.BeginTran();
                SqlsugarHelper.Instance.Deleteable<bom_opcomponentopt>()
                             .Where(p => SqlFunc.Subqueryable<bom_opcomponent>().Where(s => s.OptionsId == p.OptionsId && s.BomId == iBomid).Any())
                             .ExecuteCommand();

                SqlsugarHelper.Instance.Deleteable<bom_opcomponentsub>()
                           .Where(p => SqlFunc.Subqueryable<bom_opcomponent>().Where(s => s.OpComponentId == p.OpComponentId && s.BomId == iBomid).Any())
                           .ExecuteCommand();

                SqlsugarHelper.Instance.Deleteable<bom_opcomponent>().Where(s => s.BomId == iBomid).ExecuteCommand();
                SqlsugarHelper.Instance.CommitTran();
                //然后再进行插入

                //bom_opcomponent表
                int icnt = ItemList.Count;
                List<bom_opcomponent> bomopcomponentList = new List<bom_opcomponent>();
                List<bom_opcomponentopt> bomopcomponentoptList = new List<bom_opcomponentopt>();
                List<bom_opcomponentsub> lstsub = new List<bom_opcomponentsub>();
                int[] arrayBomChildid = DbHelper2.GetU8ID(cacc, "bom_opcomponent", icnt, conStr);
                int iopcomponentid = arrayBomChildid[1] - icnt;
                int[] arrayBomChildoptid = DbHelper2.GetU8ID(cacc, "bom_opcomponentopt", icnt, conStr);
                int iopcomponentoptid = arrayBomChildoptid[1] - icnt;
                BulidBOMChild(iBomid, out bomopcomponentList, out bomopcomponentoptList, out lstsub);

                SqlSugarClient Tardb = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = CanShu.conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                });
                try
                {
                    Tardb.BeginTran();
                    Tardb.Insertable(bomopcomponentoptList).ExecuteCommand();
                    Tardb.Insertable(bomopcomponentList).ExecuteCommand();
                    Tardb.Insertable(lstsub).ExecuteCommand();
                    Tardb.CommitTran();
                }
                catch (Exception ex)
                {
                    Tardb.RollbackTran();
                    throw ex;
                }


            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            return "ok";


        }



        /// <summary>
        /// 检查BOM是否存在
        /// </summary>
        /// <param name="cDepCode"></param>
        /// <returns></returns>
        public bool Exists(string cInvCode)
        {

            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = CanShu.conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {

                bool bExists = db.Queryable<bom_parent>()
                    .InnerJoin<bas_part>((p, inv) => p.ParentId == inv.PartId)
                    .Where((p, inv) => inv.InvCode == cInvCode).Any();

 

                return bExists;
            }
        }
        /// <summary>
        /// 根据partid取最新bomid
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public int GetBomID(int ParentId)
        {

            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = CanShu.conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {

                var bom = db.Queryable<bom_parent>()
                       .InnerJoin<bom_bom>((p, b) => p.BomId == b.BomId)
                       .Where((p, b) => p.ParentId == ParentId)
                       .OrderBy((p, b) => b.VersionEffDate).ToList()
                       .LastOrDefault();
                 if (bom!= null)
                {
                    return bom.BomId;
                }
                 else
                {
                    return 0;
                } 
            }
        }

        /// <summary>
        /// 根据bomid,子件id取最新bom行id
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public int GetOpcomponentID(int bomid,int componentid)
        {

            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = CanShu.conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {

                var bom = db.Queryable<bom_opcomponent>() 
                       .Where(o => o.BomId ==bomid && o.ComponentId==componentid)
                      .First();
                if (bom != null)
                {
                    return bom.OpComponentId;
                }
                else
                {
                    return 0;
                }




            }
        }

        /// <summary>
        /// 读取bom行
        /// </summary>
        /// <param name="bomid"></param>
        /// <returns></returns>
        public List<API_Morder.Material> GetBomOpComponent(int bomid)
        {

            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = CanShu.conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {

                var bom = db.Queryable<bom_opcomponent>()
                    .InnerJoin<bas_part>((p, b) => p.ComponentId == b.PartId)
                    .InnerJoin<bom_opcomponentopt>((p,b,opt)=>p.OptionsId==opt.OptionsId)
                     .Where((p, b, opt) => p.BomId == bomid)
                    .Select((p,b, opt) =>new API_Morder.Material {
                        cChildCode = b.InvCode,
                        Componentid = p.ComponentId,
                        dBaseQtyN = (decimal)p.BaseQtyN,
                        dQty = (decimal)p.BaseQtyD,
                        WIPType = opt.WIPType, 
                        opSeq = p.OpSeq, 
                        WhCode = opt.Whcode,
                        OpComponentId = p.OpComponentId
                    }) 
                      .ToList();
                return bom;
            }
        }
    }
}
